package com.superfish.cutieshop.activities;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.superfish.cutieshop.BaseActivity;
import com.superfish.cutieshop.BaseApp;
import com.superfish.cutieshop.BaseConfig;
import com.superfish.cutieshop.R;
import com.superfish.cutieshop.adapter.ChatAdapter;
import com.superfish.cutieshop.been.CommentInfo;
import com.superfish.cutieshop.been.ShareContent;
import com.superfish.cutieshop.been.User;
import com.superfish.cutieshop.dialog.SendDialog;
import com.superfish.cutieshop.dialog.ShareDialog;
import com.superfish.cutieshop.http.HttpStores;
import com.superfish.cutieshop.http.ZokeParams;
import com.superfish.cutieshop.parser.GsonAddComment;
import com.superfish.cutieshop.parser.GsonComments;
import com.superfish.cutieshop.parser.GsonFavorite;
import com.superfish.cutieshop.utils.CommonUtil;
import com.superfish.cutieshop.utils.CutieToast;
import com.superfish.cutieshop.utils.HttpParams;
import com.superfish.cutieshop.utils.LogTest;
import com.superfish.cutieshop.utils.TaobaoUtils;
import com.superfish.cutieshop.utils.TimeUtils;
import com.superfish.cutieshop.utils.UserInfo;
import com.superfish.cutieshop.view.UserDetailRelativeLayout;
import com.superfish.cutieshop.view.pulltorefresh.PullToRefreshBase;
import com.superfish.cutieshop.view.pulltorefresh.PullToRefreshScrollView;
import com.umeng.analytics.MobclickAgent;

import org.w3c.dom.Text;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 攻略详情页面 JackWu
 */
@ContentView(R.layout.activity_strategy_detail)
public class StrategyDetailActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener2<ScrollView> {
    @ViewInject(R.id.toolbar)
    private Toolbar mToolbar;
    @ViewInject(R.id.webView)
    private WebView mWebView;
    @ViewInject(R.id.listView)
    private ListView mListView;
    private List<CommentInfo> mList = new LinkedList<>();
    private ChatAdapter mAdapter;
    @ViewInject(R.id.sendBtn)
    private TextView mSendTv;
    @ViewInject(R.id.container)
    private PullToRefreshScrollView mPullView;
    private ShareDialog shareDialog;
    private String title;
    private String shareUrl;
    private int iid;
    private int count;//有多少人添加了心愿清单
    private boolean isFav;
    @ViewInject(R.id.likeNum)
    private TextView mLikeNum;
    @ViewInject(R.id.likeBtn)
    private ImageView mLikeIv;
    private int mPage;//页码
    @ViewInject(R.id.edit)
    private TextView mEdit;
    private String url;
    private boolean isFailed;//如果这个失败了 则弹幕也不开启
    @ViewInject(R.id.keyContainer)
    private UserDetailRelativeLayout mKeyContainer;

    @ViewInject(R.id.commentContainer)
    private View mCommentContainer;

    @ViewInject(R.id.likeContainer)
    private View mLikeContainer;

    private boolean hasMore;

    private boolean isShowFav;
    private String imageUrl;
    private String dec;

    public static void open(Activity act, String title, String shareUrl, int iid, int count, boolean isFav, String url, boolean isShowFav, String imageUrl, String dec) {
        Intent i = new Intent(act, StrategyDetailActivity.class);
        i.putExtra("title", title);
        i.putExtra("shareUrl", shareUrl);
        i.putExtra("iid", iid);
        i.putExtra("count", count);
        i.putExtra("isFav", isFav);
        i.putExtra("url", url);
        i.putExtra("isShowFav", isShowFav);
        i.putExtra("imageUrl", imageUrl);
        i.putExtra("dec", dec);
        open(act, i);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        title = getIntent().getStringExtra("title");
        shareUrl = getIntent().getStringExtra("shareUrl");
        iid = getIntent().getIntExtra("iid", -1);
        count = getIntent().getIntExtra("count", 0);
        isFav = getIntent().getBooleanExtra("isFav", false);
        url = getIntent().getStringExtra("url");
        isShowFav = getIntent().getBooleanExtra("isShowFav", false);
        imageUrl = getIntent().getStringExtra("imageUrl");
        dec = getIntent().getStringExtra("dec");
        mLikeContainer.setVisibility(isShowFav ? View.VISIBLE : View.GONE);
        mToolbar.setTitle("");
        setAppTitle("");
        mToolbar.setNavigationIcon(R.drawable.btn_back_bar);
        //动态设置颜色 根据当前星期时间设置
        mToolbar.setBackgroundColor(getResources().getColor(TimeUtils.aTheme()));
        getStatusBar().setBackgroundColor(getResources().getColor(TimeUtils.aTheme()));
        //变色
        mCommentContainer.setBackgroundResource(TimeUtils.getComments(new Date().getTime()));
        setSupportActionBar(mToolbar);
        //
        mLikeNum.setText(count + "人添加到心愿单");
        mLikeIv.setImageResource(isFav ? R.drawable.btn_like : R.drawable.btn_unlike_);
        shareDialog = new ShareDialog(this);
        mPullView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        mPullView.setOnRefreshListener(this);
        ScrollView mScrollView = mPullView.getRefreshableView();
        if (android.os.Build.VERSION.SDK_INT > 8) {// 判断sdk版本
            mScrollView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        } else {
            mScrollView.setFadingEdgeLength(0);
        }
        mWebView.loadUrl(url);
        mSendTv.setBackgroundResource(TimeUtils.getComments(new Date().getTime()));
        mAdapter = new ChatAdapter(this, mList);
        mListView.setAdapter(mAdapter);
        intiWebSettings();
        initListener();
        mPage = 0;
        fetchComments(mPage);
        mKeyContainer.setOnKeyBoardChangeListener(new UserDetailRelativeLayout.OnKeyboardChangeListener() {
            @Override
            public void onKeyboardShow() {
                LogTest.wlj("执行 onKeyboardShow");
            }

            @Override
            public void onKeyboardHide() {
                LogTest.wlj("执行 onKeyboardHide");
            }
        });
    }


    /**
     * 设置WebSettings
     **/
    private void intiWebSettings() {
        if (android.os.Build.VERSION.SDK_INT > 8) {// 判断sdk版本，使用不用的api消除fedingedge
            mWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        } else {
            mWebView.setFadingEdgeLength(0);
        }
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setSupportZoom(false);
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDatabasePath(BaseApp.getTempCache(this));
        webSettings.setAppCachePath(BaseApp.getTempCache(this));
        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);// 设置缓冲大小，8M
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(false);
        mWebView.setDownloadListener(new DownloadListener() {//  使用自带的浏览器下载文件
            @Override
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimetype,
                                        long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
    }

    /**
     * 设置WebView的一些监听
     **/
    private void initListener() {
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (isFailed) {
                    showNetFail();
                    return;
                }
                showContent();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                showLoading();
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                LogTest.wlj("onReceivedError=" + errorCode);
                isFailed = true;
                switch (errorCode) {
                    case WebViewClient.ERROR_TIMEOUT:
                    case WebViewClient.ERROR_CONNECT:
                    case WebViewClient.ERROR_HOST_LOOKUP:
                        // 没网
                        showNetFail();
                        break;
                    default:
                        // 没数据
                        break;
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogTest.wlj("url=" + url);
//                  拦截Url 进行判断 处理业务逻辑
//                mWebView.loadUrl(url);
                if (url.contains("openId=")) {
                    //买买买
                    String[] buys = url.split("openId=");

                    if (buys != null && buys.length != 0) {
                        String by = buys[1];
                        LogTest.wlj("by=" + by);
                        String[] bys = by.split("&from=");
                        if (bys != null && bys.length != 0) {
                            LogTest.wlj("id = " + bys[0] + "类型=" + bys[1]);
                            buy(bys[0], "tmall".equals(bys[1]) ? TaobaoUtils.TIANMAO : TaobaoUtils.TAOBAO);
                        }
                    }
                    return true;
                }

                if (url.contains("shareType=")) {
                    //分享
                    String[] shares = url.split("shareType=");
                    LogTest.wlj("" + shares[1]);
                    if (shares != null && shares.length != 0) {
//                        share(shares[1]);
                    }
                    return true;
                }

                if (url.contains("tid=")) {
                    String[] tids = url.split("tid=");
                    if (tids != null && tids.length != 0) {
                        int tid = Integer.parseInt(tids[1]);
                        finish();
                    }
                    return true;
                }

                //本页面加载Url
                mWebView.loadUrl(url);
                return true;
            }

        });

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_strategy, menu);
        return true;
    }


    public void showLoading() {
        mPageState.showLoading();
        mPullView.setVisibility(View.GONE);
        mPageState.setOnReloadListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isFailed = false;
                showLoading();
                mWebView.loadUrl(url);
                mPage = 0;
                fetchComments(mPage);
            }
        });
    }

    public void showNetFail() {
        mPageState.showNetFailed();
        mPullView.setVisibility(View.GONE);
    }

    public void showContent() {
        mPageState.hide();
        mPullView.setVisibility(View.VISIBLE);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_share) {
            //分享
            MobclickAgent.onEvent(this, BaseConfig.UM.GM_SHARE_DES);
            ShareContent sc = ShareContent.getPhaseShareContent(iid, title, shareUrl, imageUrl, dec);
            shareDialog.setShareContent(sc);
            shareDialog.show();
            return true;
        }
        if (id == R.id.action_like) {
            //我的
            UserProfileActivity.open(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 跳转淘宝购买
     **/
    public void buy(String openId, int type) {
        if (!CommonUtil.getNetWorkStates(this)) {
            CutieToast.showNetFailed(getApplicationContext());
            return;
        }
        LogTest.wlj("类型=" + type);
        LogTest.lmh("类型=" + type);
        LogTest.lmh("类型=" + openId);
        TaobaoUtils.showTaokeItemDetail(this, type, openId);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        mPullView.onRefreshComplete();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        if (!hasMore) {
            CutieToast.showNoMore(this);
            mPullView.onRefreshComplete();
            return;
        }

        //加载更多
        mPage++;
        fetchComments(mPage);
    }


    @OnClick(R.id.likeBtn)
    public void onClickLike(View v) {
        MobclickAgent.onEvent(this, BaseConfig.UM.GM_FAV_DES);
        if (BaseApp.isGuest()) {
            LoginActivity.open(this);
            return;
        }

        if (!CommonUtil.getNetWorkStates(this)) {
            CutieToast.showNetFailed(this);
            return;
        }
        ZokeParams params = HttpParams.addDetail(mHashCode, isFav ? 1 : 0, iid);
        HttpStores.getInstense().post(params);
        //处理状态提前量 --
        mLikeIv.setImageResource(!isFav ? R.drawable.btn_like : R.drawable.btn_unlike_);
    }

    @OnClick(R.id.sendContainer)
    public void onClickSend(View v) {
        sendComment();
    }


    private void sendComment() {
        MobclickAgent.onEvent(this, BaseConfig.UM.GM_COMMENT_DES);
        String content = mEdit.getText().toString();
        CommonUtil.hideKeyboard(mEdit);
        if (TextUtils.isEmpty(content)) {
            CutieToast.show(this, R.string.global_content_no);
            return;
        }
        if (BaseApp.isGuest()) {
            LoginActivity.open(this);
            return;
        }
        if (!CommonUtil.getNetWorkStates(this)) {
            CutieToast.showNetFailed(this);
            return;
        }
        User user = UserInfo.getInstense(this).getUser();
        if (user == null) {
            LoginActivity.open(this);
            return;
        }
        mEdit.setText("");
        fetchAddComment(content);
    }

    /**
     * 获取评论列表
     **/
    private void fetchComments(int page) {
        ZokeParams params = HttpParams.getComments(mHashCode, iid, page);
        HttpStores.getInstense().get(params);
    }

    /**
     * 添加评论
     **/
    private void fetchAddComment(String text) {
        ZokeParams params = HttpParams.getAddComments(mHashCode, iid, text);
        HttpStores.getInstense().post(params);
    }

    @Override
    public void onSuccess(ZokeParams out) {
        super.onSuccess(out);
        String url = out.getUrl();
        ResponseInfo res = (ResponseInfo) out.getResult();
        String result = (String) res.result;
        LogTest.wlj("result=" + result);
        if (url.equals(BaseConfig.UrlBank.comments)) {
            //评论列表
            GsonComments gc = new GsonComments().fromJson(result);
            if (gc.info == null || gc.info.list == null || gc.info.list.length == 0 || gc.error_code != 0) {
                return;
            }
            for (CommentInfo cI : gc.info.list) {
                mList.add(cI);
            }
            notifyChat();
            mAdapter.notifyDataSetChanged();
            mPullView.onRefreshComplete();
            if (mPage != 0) {
                scrollToBottom();
            }
            hasMore = gc.info.next_page == 1;
            return;
        }

        if (url.equals(BaseConfig.UrlBank.addComment)) {
            GsonAddComment gadd = new GsonAddComment().fromJson(result);
            if (gadd.info == null || gadd.error_code != 0) {
                return;
            }
            CommentInfo ci = gadd.info;
            ci.msgType = 1;
            mList.add(ci);
            mAdapter = new ChatAdapter(this, mList);
            mListView.setAdapter(mAdapter);
            scrollToBottom();
            hasMore = false;
            return;
        }


        if (url.equals(BaseConfig.UrlBank.addDetail)) {
            GsonFavorite gf = new GsonFavorite().fromJson(result);
            if (gf.info == null || gf.error_code != 0) {
                mLikeIv.setImageResource(isFav ? R.drawable.btn_like : R.drawable.btn_unlike_);
                return;
            }
            //  status 0没有，1有
            isFav = gf.info.status == 1;
            mLikeIv.setImageResource(isFav ? R.drawable.btn_like : R.drawable.btn_unlike_);
            count = isFav ? count + 1 : count - 1;//
            mLikeNum.setText(count + "人添加到心愿单");
            return;
        }
    }

    private void scrollToBottom() {
        final ScrollView scrollView = mPullView.getRefreshableView();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }

    /**
     * 更新聊天
     **/
    private void notifyChat() {
        User user = null;
        for (CommentInfo cI : mList) {
            if (BaseApp.isGuest()) {
                cI.msgType = 2;//默认是接收
            } else {
                if (user == null) {
                    user = UserInfo.getInstense(StrategyDetailActivity.this).getUser();
                }
                if (cI.user_info.uid == user.uid) {
                    cI.msgType = 1;//发送人的uid和当前User的Uid相同是发送者
                } else {
                    cI.msgType = 2;// 不同是接收者
                }
            }
        }
    }

    @Override
    public void onFails(ZokeParams out) {
        super.onFails(out);
        String url = out.getUrl();
        if (url.equals(BaseConfig.UrlBank.comments)) {
            //评论列表拉取失败了
            CutieToast.showNetFailed(this);
            showNetFail();
            return;
        }

        if (url.equals(BaseConfig.UrlBank.addComment)) {
            CutieToast.showNetFailed(this);
            return;
        }

        if (url.equals(BaseConfig.UrlBank.addDetail)) {
            CutieToast.show(this, "操作失败");
            //回退状态
            mLikeIv.setImageResource(isFav ? R.drawable.btn_like : R.drawable.btn_unlike_);
            return;
        }
    }

    @OnClick(R.id.edit)
    public void onClickComment(View v) {
        SendDialog mdialog = new SendDialog(this);
        if (!TextUtils.isEmpty(mEdit.getText().toString())) {
            mdialog.setEditContent(mEdit.getText().toString());
        }
        mdialog.setSendListener(new SendDialog.SendListener() {
            @Override
            public void send(String text) {
                // 发送
                mEdit.setText(text);
                sendComment();
            }

            @Override
            public void dissmiss(String text, boolean isSend) {
                //隐藏
                if (!TextUtils.isEmpty(text) && !isSend) {
                    mEdit.setText(text);
                }
            }
        });
        mdialog.show();
    }
}
